package My

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

func (my TableInfoMeta) TableName(s global.TablesMetaInfoInput) (result global.ObjectNameReturnResult, err error) {
	var f1 any
	var event = "[MySQLTableName]"
	result.BaseResult.Sql = fmt.Sprintf("select table_NAME as `tableName` from information_Schema.TABLES where TABLE_TYPE = 'BASE TABLE'  AND table_schema ='%v' %v",
		s.TableInfo.Schema, func() string {
			switch {
			case s.TableInfo.Table == "*":
				return ""
			case strings.Contains(s.TableInfo.Table, "%"):
				return fmt.Sprintf("and table_name like '%%%v%%'", s.TableInfo.Table)
			default:
				return fmt.Sprintf("and table_name = '%v'", s.TableInfo.Table)
			}
		}())
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.StringGarth,
	}); err != nil || f1 == nil || len(f1.([]string)) == 0 {
		return
	}
	result.Result = f1.([]string)
	return
}

func (my TableInfoMeta) TableExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var f1 any
	var event = "[MySQLTableExist]"
	result.BaseResult.Sql = fmt.Sprintf("select count(1) as `sum` from information_Schema.TABLES where TABLE_TYPE = 'BASE TABLE'  AND table_schema ='%v'  and table_NAME = '%v'", s.TableInfo.Schema, s.TableInfo.Table)
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil || len(f1.(map[string]any)) == 0 {
		return
	}
	if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
		result.Result = true
	}
	return
}

func (my TableInfoMeta) DataBaseExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var f1 any
	var event = "[MySQLDataBaseExist]"
	result.BaseResult.Sql = fmt.Sprintf("SELECT  count(1) as `sum` FROM information_schema.tables WHERE TABLE_TYPE = 'BASE TABLE'  AND table_schema = '%v' ", s.TableInfo.Schema)
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil || len(f1.(map[string]any)) == 0 {
		return
	}
	if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
		result.Result = true
	}
	return
}
